// 数据管理页面JavaScript
class DataManagement {
    constructor() {
        this.currentPage = 1;
        this.pageSize = 20;
        this.totalPages = 1;
        this.filters = {};
        this.sortField = 'crawl_time';
        this.sortOrder = 'DESC';

        this.init();
    }

    init() {
        this.bindEvents();
        this.loadStats();
        this.loadHouses();
    }

    bindEvents() {
        // 搜索表单提交
        $('#searchForm').on('submit', (e) => {
            e.preventDefault();
            this.currentPage = 1;
            this.updateFilters();
            this.loadHouses();
        });

        // 切换收藏状态
$('#housesTableBody').on('click', '.toggle-favorite', (e) => {
    const button = $(e.currentTarget);
    const houseId = button.data('id');
    this.toggleFavorite(houseId, button);
});

        // 重置筛选条件
        $('#resetFilters').on('click', () => {
            this.resetFilters();
        });

        // 城市选择变化时加载区域
        $('#filterCity').on('change', () => {
            this.loadDistricts($('#filterCity').val());
        });

        // 分页大小变化
        $('#pageSize').on('change', () => {
            this.pageSize = parseInt($('#pageSize').val());
            this.currentPage = 1;
            this.loadHouses();
        });

        // 导出数据
        $('#exportData').on('click', () => {
            this.exportData();
        });

        // 编辑房源按钮
        $('#editHouseBtn').on('click', () => {
            this.showEditModal();
        });

        // 保存房源信息
        $('#saveHouseBtn').on('click', () => {
            this.saveHouse();
        });

        // 删除房源
        $('#deleteHouseBtn').on('click', () => {
            this.deleteHouse();
        });
    }

    updateFilters() {
        this.filters = {
            search: $('#searchKeyword').val().trim(),
            city: $('#filterCity').val(),
            district: $('#filterDistrict').val(),
            room_type: $('#filterRoomType').val(),
            source_type: $('#filterSourceType').val(),
            min_price: $('#minPriceFilter').val() ? parseFloat($('#minPriceFilter').val()) : 0,
            max_price: $('#maxPriceFilter').val() ? parseFloat($('#maxPriceFilter').val()) : 0,
             is_favorite: $('#filterFavorite').val()  // 添加收藏状态筛选
        };

        this.sortField = $('#sortField').val();
        this.sortOrder = $('#sortOrder').val();
    }

    resetFilters() {
        $('#searchKeyword').val('');
        $('#filterCity').val('');
        $('#filterDistrict').val('');
        $('#filterRoomType').val('');
        $('#filterSourceType').val('');
        $('#minPriceFilter').val('');
        $('#maxPriceFilter').val('');
          $('#filterFavorite').val('');  // 重置收藏状态筛选
        $('#sortField').val('crawl_time');
        $('#sortOrder').val('DESC');

        this.filters = {};
        this.currentPage = 1;
        this.loadHouses();
    }

    async loadDistricts(city) {
        if (!city) {
            $('#filterDistrict').html('<option value="">全部区域</option>');
            return;
        }

        try {
            const response = await fetch(`/get_city_districts/${city}`);
            const data = await response.json();

            let options = '<option value="">全部区域</option>';
            data.districts.forEach(district => {
                options += `<option value="${district}">${district}</option>`;
            });
            $('#filterDistrict').html(options);
        } catch (error) {
            console.error('加载区域失败:', error);
        }
    }

    async toggleFavorite(houseId, button) {
    try {
        const response = await fetch(`/api/houses/${houseId}/favorite`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            }
        });
        const data = await response.json();

        if (data.success) {
            // 更新按钮状态
            const isFavorite = data.data.is_favorite;
            button.toggleClass('btn-danger btn-outline-secondary');
            button.attr('title', isFavorite ? '取消收藏' : '收藏');

            // 更新行中的收藏图标
            const icon = button.closest('tr').find('td:nth-child(10) i');
            icon.toggleClass('fas far text-danger text-muted');

            // 如果当前有收藏筛选，重新加载数据以保持筛选状态
            if ($('#filterFavorite').val()) {
                this.loadHouses();
            }
        } else {
            throw new Error(data.message);
        }
    } catch (error) {
        console.error('切换收藏状态失败:', error);
        alert('操作失败: ' + error.message);
    }
}

    async loadStats() {
        try {
            const response = await fetch('/api/houses/stats');
            const data = await response.json();

            if (data.success) {
                const stats = data.data;
                $('#totalCount').text(stats.total_count.toLocaleString());

                if (stats.price_stats && stats.price_stats.avg_price) {
                    $('#avgPrice').text('¥' + Math.round(stats.price_stats.avg_price).toLocaleString());
                } else {
                    $('#avgPrice').text('暂无数据');
                }

                $('#cityCount').text(stats.city_distribution.length);
                $('#lastUpdate').text('今日');
            }
        } catch (error) {
            console.error('加载统计信息失败:', error);
            $('#totalCount').text('加载失败');
            $('#avgPrice').text('加载失败');
            $('#cityCount').text('加载失败');
            $('#lastUpdate').text('加载失败');
        }
    }

    async loadHouses() {
        const tbody = $('#housesTableBody');
        tbody.html(`
            <tr>
                <td colspan="10" class="text-center py-4">
                    <div class="spinner-border text-primary" role="status">
                        <span class="visually-hidden">加载中...</span>
                    </div>
                    <p class="mt-2 mb-0">数据加载中...</p>
                </td>
            </tr>
        `);

        try {
            const params = new URLSearchParams({
                page: this.currentPage,
                per_page: this.pageSize,
                sort_field: this.sortField,
                sort_order: this.sortOrder,
                ...this.filters
            });

            const response = await fetch(`/api/houses?${params}`);
            const data = await response.json();

            if (data.success) {
                this.renderHouses(data.data);
                this.renderPagination(data.pagination);
            } else {
                throw new Error(data.message);
            }
        } catch (error) {
            console.error('加载房源数据失败:', error);
            tbody.html(`
                <tr>
                    <td colspan="10" class="text-center py-4 text-danger">
                        <i class="fas fa-exclamation-triangle me-2"></i>
                        加载失败: ${error.message}
                    </td>
                </tr>
            `);
        }
    }

    renderHouses(houses) {
    console.log('渲染房源数据:', houses);
    const tbody = $('#housesTableBody');

    if (!houses || houses.length === 0) {
        tbody.html(`
            <tr>
                <td colspan="12" class="text-center py-4 text-muted">
                    <i class="fas fa-inbox me-2"></i>
                    暂无数据
                </td>
            </tr>
        `);
        return;
    }

    let html = '';
    houses.forEach(house => {
        // 处理标题显示，确保不会太长
        let title = house.title || '无标题';
        let shortTitle = title.length > 30 ? title.substring(0, 30) + '...' : title;

        // 处理价格显示
        let price = house.price || 0;
        let priceText = price > 0 ? `¥${price.toLocaleString()}` : '价格面议';

        // 处理面积显示
        let areaText = house.area ? `${house.area}㎡` : '-';

        // 检查是否有有效链接
        const hasValidLink = house.link && house.link.startsWith('http');

        // 收藏状态图标
        const isFavorite = house.is_favorite || false; // 默认 false
        const favoriteIcon = house.is_favorite ?
            '<i class="fas fa-heart text-danger" title="已收藏"></i>' :
            '<i class="far fa-heart text-muted" title="未收藏"></i>';

        html += `
            <tr>
                <td>
                    <input type="checkbox" class="house-checkbox" value="${house.id}">
                </td>
                <td>
                    <small class="text-muted">${house.id || ''}</small>
                </td>
                <td>
                    <div title="${title}">
                        ${shortTitle}
                    </div>
                </td>
                <td>
                    <span class="badge bg-success">${priceText}</span>
                </td>
                <td>${house.room_type || '-'}</td>
                <td>${areaText}</td>
                <td>${house.city || '-'}</td>
                <td>${house.district || '-'}</td>
                <td>
                    <span class="badge bg-info">${this.getSourceTypeText(house.source_type)}</span>
                </td>
                <td>
                    ${favoriteIcon}  <!-- 显示收藏状态图标 -->
                </td>
                <td>
                    <small class="text-muted">${house.crawl_time || '-'}</small>
                </td>
                <td>
                    <div class="btn-group btn-group-sm">
                        <button class="btn btn-outline-primary view-detail"
                                data-id="${house.id}" title="查看详情">
                            <i class="fas fa-eye"></i>
                        </button>
                        <button class="btn btn-outline-warning edit-house"
                                data-id="${house.id}" title="编辑">
                            <i class="fas fa-edit"></i>
                        </button>
                        ${hasValidLink ?
                            `<a class="btn btn-outline-info external-link"
                                href="${house.link}"
                                target="_blank"
                                title="查看原始页面"
                                data-link="${house.link}">
                                <i class="fas fa-external-link-alt"></i>
                            </a>` :
                            `<button class="btn btn-outline-secondary" disabled title="无原始链接">
                                <i class="fas fa-external-link-alt"></i>
                            </button>`
                        }
                        <button class="btn ${house.is_favorite ? 'btn-danger' : 'btn-outline-secondary'} toggle-favorite"
                                data-id="${house.id}"
                                title="${house.is_favorite ? '取消收藏' : '收藏'}">
                            <i class="fas fa-heart"></i>
                        </button>
                    </div>
                </td>
            </tr>
        `;
    });

    tbody.html(html);

    // 绑定事件
    this.bindHouseEvents();
}

    // 然后，我们添加一个方法用于绑定复选框事件和操作按钮事件
bindHouseEvents() {
    // 绑定查看详情事件
    $('.view-detail').off('click').on('click', (e) => {
        const houseId = $(e.currentTarget).data('id');
        this.showHouseDetail(houseId);
    });

    // 绑定编辑事件
    $('.edit-house').off('click').on('click', (e) => {
        const houseId = $(e.currentTarget).data('id');
        this.showEditModal(houseId);
    });

        // 绑定外部链接点击事件（用于统计等）
    $('.external-link').off('click').on('click', (e) => {
        const link = $(e.currentTarget).data('link');
        console.log('用户点击外部链接:', link);
        // 这里可以添加点击统计代码
    });

    // 绑定复选框事件
    $('.house-checkbox').off('change').on('change', () => {
        this.updateBatchActions();
    });

    // 全选/全不选
    $('#selectAll').off('change').on('change', (e) => {
        const isChecked = $(e.target).is(':checked');
        $('.house-checkbox').prop('checked', isChecked);
        this.updateBatchActions();
    });
}

// 批量删除房源
async batchDeleteHouses() {
    const selectedIds = [];
    $('.house-checkbox:checked').each(function() {
        selectedIds.push(parseInt($(this).val()));
    });

    if (selectedIds.length === 0) {
        alert('请选择要删除的房源');
        return;
    }

    if (!confirm(`确定要删除选中的 ${selectedIds.length} 条房源记录吗？此操作不可恢复。`)) {
        return;
    }

    try {
        $('#batchDeleteBtn').prop('disabled', true).html('<i class="fas fa-spinner fa-spin me-1"></i>删除中...');

        const response = await fetch('/api/houses/batch_delete', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ ids: selectedIds })
        });

        const result = await response.json();

        if (result.success) {
            alert(result.message);
            $('#batchActions').addClass('d-none');
            this.loadHouses(); // 刷新列表
            this.loadStats(); // 刷新统计
        } else {
            throw new Error(result.message);
        }

    } catch (error) {
        alert('批量删除失败: ' + error.message);
    } finally {
        $('#batchDeleteBtn').prop('disabled', false).html('<i class="fas fa-trash me-1"></i>批量删除');
    }
}

// 更新批量操作按钮状态
updateBatchActions() {
    const selectedCount = $('.house-checkbox:checked').length;
    const batchActions = $('#batchActions');

    if (selectedCount > 0) {
        if (!batchActions.length) {
            // 添加批量操作工具栏
            const toolbar = `
                <div class="card mb-3" id="batchActions">
                    <div class="card-body py-2">
                        <div class="d-flex align-items-center">
                            <span class="me-3">已选择 <strong>${selectedCount}</strong> 项</span>
                            <button class="btn btn-outline-danger btn-sm me-2" id="batchDeleteBtn">
                                <i class="fas fa-trash me-1"></i>批量删除
                            </button>
                            <button class="btn btn-outline-secondary btn-sm" id="clearSelection">
                                <i class="fas fa-times me-1"></i>取消选择
                            </button>
                        </div>
                    </div>
                </div>
            `;
            $('#housesTable').before(toolbar);

            // 绑定批量删除事件
            $('#batchDeleteBtn').on('click', () => {
                this.batchDeleteHouses();
            });

            // 绑定取消选择事件
            $('#clearSelection').on('click', () => {
                $('.house-checkbox').prop('checked', false);
                $('#selectAll').prop('checked', false);
                batchActions.remove();
            });
        } else {
            // 更新数量
            batchActions.find('strong').text(selectedCount);
        }
    } else {
        batchActions.remove();
    }
}

    renderPagination(pagination) {
        const paginationEl = $('#pagination');
        const { page, pages, total } = pagination;

        this.totalPages = pages;

        if (pages <= 1) {
            paginationEl.hide();
            return;
        }

        paginationEl.show();

        let html = '';

        // 上一页
        if (page > 1) {
            html += `<li class="page-item"><a class="page-link" href="#" data-page="${page - 1}">上一页</a></li>`;
        } else {
            html += `<li class="page-item disabled"><a class="page-link" href="#">上一页</a></li>`;
        }

        // 页码
        const startPage = Math.max(1, page - 2);
        const endPage = Math.min(pages, page + 2);

        for (let i = startPage; i <= endPage; i++) {
            if (i === page) {
                html += `<li class="page-item active"><a class="page-link" href="#">${i}</a></li>`;
            } else {
                html += `<li class="page-item"><a class="page-link" href="#" data-page="${i}">${i}</a></li>`;
            }
        }

        // 下一页
        if (page < pages) {
            html += `<li class="page-item"><a class="page-link" href="#" data-page="${page + 1}">下一页</a></li>`;
        } else {
            html += `<li class="page-item disabled"><a class="page-link" href="#">下一页</a></li>`;
        }

        paginationEl.html(html);

        // 绑定分页点击事件
        paginationEl.find('.page-link[data-page]').on('click', (e) => {
            e.preventDefault();
            this.currentPage = parseInt($(e.currentTarget).data('page'));
            this.loadHouses();
        });
    }

    getSourceTypeText(sourceType) {
        const sourceMap = {
            'l1': '经纪房源',
            'l2': '个人房源',
            'jg1': '品牌公寓'
        };
        return sourceMap[sourceType] || sourceType || '未知';
    }

    async showHouseDetail(houseId) {
        const modalContent = $('#houseDetailContent');
        modalContent.html(`
            <div class="text-center py-4">
                <div class="spinner-border text-primary" role="status">
                    <span class="visually-hidden">加载中...</span>
                </div>
                <p class="mt-2 mb-0">加载中...</p>
            </div>
        `);

        $('#houseDetailModal').modal('show');

        try {
            const response = await fetch(`/api/houses/${houseId}`);
            const data = await response.json();

            if (data.success) {
                this.renderHouseDetail(data.data);
            } else {
                throw new Error(data.message);
            }
        } catch (error) {
            modalContent.html(`
                <div class="alert alert-danger">
                    <i class="fas fa-exclamation-triangle me-2"></i>
                    加载失败: ${error.message}
                </div>
            `);
        }
    }

    renderHouseDetail(house) {
        const modalContent = $('#houseDetailContent');

        // 检查是否有有效链接
    const hasValidLink = house.link && house.link.startsWith('http');

        let html = `
            <div class="row">
                <div class="col-md-6">
                    <h6>基本信息</h6>
                    <table class="table table-sm">
                        <tr><td><strong>标题:</strong></td><td>${house.title || '-'}</td></tr>
                        <tr><td><strong>价格:</strong></td><td>¥${house.price || 0}/月</td></tr>
                        <tr><td><strong>户型:</strong></td><td>${house.room_type || '-'}</td></tr>
                        <tr><td><strong>面积:</strong></td><td>${house.area || '-'} ㎡</td></tr>
                        <tr><td><strong>楼层:</strong></td><td>${house.floor_info || '-'}</td></tr>
                    </table>
                </div>
                <div class="col-md-6">
                    <h6>位置信息</h6>
                    <table class="table table-sm">
                        <tr><td><strong>城市:</strong></td><td>${house.city || '-'}</td></tr>
                        <tr><td><strong>区域:</strong></td><td>${house.district || '-'}</td></tr>
                        <tr><td><strong>地址:</strong></td><td>${house.address || '-'}</td></tr>
                        <tr><td><strong>来源:</strong></td><td>${this.getSourceTypeText(house.source_type)}</td></tr>
                        <tr><td><strong>经纪人:</strong></td><td>${house.agent || '-'}</td></tr>
                    </table>
                </div>
            </div>
        `;

        if (house.description || house.features || house.facilities) {
            html += `
                <div class="row mt-3">
                    <div class="col-12">
                        <h6>详细信息</h6>
                        ${house.description ? `<p><strong>描述:</strong> ${house.description}</p>` : ''}
                        ${house.features ? `<p><strong>特色:</strong> ${house.features}</p>` : ''}
                        ${house.facilities ? `<p><strong>设施:</strong> ${house.facilities}</p>` : ''}
                        ${house.rental_requirements ? `<p><strong>出租要求:</strong> ${house.rental_requirements}</p>` : ''}
                    </div>
                </div>
            `;
        }

        html += `
            <div class="row mt-3">
                <div class="col-12">
                    <h6>系统信息</h6>
                    <table class="table table-sm">
                        <tr><td><strong>房屋编码:</strong></td><td>${house.house_code || '-'}</td></tr>
                        <tr><td><strong>爬取时间:</strong></td><td>${house.crawl_time || '-'}</td></tr>
                        <tr><td><strong>创建时间:</strong></td><td>${house.created_at || '-'}</td></tr>
                        <tr><td><strong>更新时间:</strong></td><td>${house.updated_at || '-'}</td></tr>
                    </table>
                </div>
            </div>
        `;

        // 外部链接按钮
    if (hasValidLink) {
        html += `
            <div class="row mt-3">
                <div class="col-12">
                    <a href="${house.link}" target="_blank" class="btn btn-outline-primary">
                        <i class="fas fa-external-link-alt me-2"></i>查看原始页面
                    </a>
                </div>
            </div>
        `;
    }

        modalContent.html(html);

        // 设置编辑按钮的数据
        $('#editHouseBtn').data('id', house.id);
    }

    async showEditModal(houseId = null) {
        if (houseId) {
            // 编辑现有房源
            try {
                const response = await fetch(`/api/houses/${houseId}`);
                const data = await response.json();

                if (data.success) {
                    this.fillEditForm(data.data);
                    $('#editHouseModal').modal('show');
                } else {
                    throw new Error(data.message);
                }
            } catch (error) {
                alert('加载房源信息失败: ' + error.message);
            }
        } else {
            // 创建新房源（清空表单）
            this.fillEditForm({});
            $('#editHouseModal').modal('show');
        }
    }

    fillEditForm(house) {
        $('#editHouseId').val(house.id || '');
        $('#editTitle').val(house.title || '');
        $('#editPrice').val(house.price || '');
        $('#editRoomType').val(house.room_type || '');
        $('#editArea').val(house.area || '');
        $('#editCity').val(house.city || '');
        $('#editDistrict').val(house.district || '');
        $('#editAddress').val(house.address || '');
        $('#editSourceType').val(house.source_type || '');
        $('#editDescription').val(house.description || '');
        $('#editFeatures').val(house.features || '');

        // 设置删除按钮的数据
        $('#deleteHouseBtn').data('id', house.id || '');
    }

    async saveHouse() {
        const formData = {
        id: $('#editHouseId').val(),
        title: $('#editTitle').val(),
        price: parseFloat($('#editPrice').val()) || 0,
        room_type: $('#editRoomType').val(),
        area: parseFloat($('#editArea').val()) || 0,
        city: $('#editCity').val(),
        district: $('#editDistrict').val(),
        address: $('#editAddress').val(),
        source_type: $('#editSourceType').val(),
        description: $('#editDescription').val(),
        features: $('#editFeatures').val()
        };

        // 验证必填字段
    if (!formData.title.trim()) {
        alert('请输入房源标题');
        return;
    }

    if (!formData.price || formData.price <= 0) {
        alert('请输入有效的价格');
        return;
    }

    try {
        $('#saveHouseBtn').prop('disabled', true).html('<i class="fas fa-spinner fa-spin me-1"></i>保存中...');

        let response;
        if (formData.id) {
            // 更新现有房源
            response = await fetch(`/api/houses/${formData.id}`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(formData)
            });
        } else {
            // 创建新房源（这里暂时不支持创建，只支持更新）
            alert('目前仅支持编辑现有房源');
            $('#saveHouseBtn').prop('disabled', false).html('保存');
            return;
        }

        const result = await response.json();

        if (result.success) {
            alert('保存成功！');
            $('#editHouseModal').modal('hide');
            this.loadHouses(); // 刷新列表
            this.loadStats(); // 刷新统计
        } else {
            throw new Error(result.message);
        }

    } catch (error) {
        alert('保存失败: ' + error.message);
    } finally {
        $('#saveHouseBtn').prop('disabled', false).html('保存');
    }
    }

    async deleteHouse() {
        const houseId = $('#deleteHouseBtn').data('id');

    if (!houseId) {
        alert('无效的房源ID');
        return;
    }

    if (!confirm('确定要删除这条房源信息吗？此操作不可恢复。')) {
        return;
    }

    try {
        $('#deleteHouseBtn').prop('disabled', true).html('<i class="fas fa-spinner fa-spin me-1"></i>删除中...');

        const response = await fetch(`/api/houses/${houseId}`, {
            method: 'DELETE'
        });

        const result = await response.json();

        if (result.success) {
            alert('删除成功！');
            $('#editHouseModal').modal('hide');
            this.loadHouses(); // 刷新列表
            this.loadStats(); // 刷新统计
        } else {
            throw new Error(result.message);
        }

    } catch (error) {
        alert('删除失败: ' + error.message);
    } finally {
        $('#deleteHouseBtn').prop('disabled', false).html('删除');
    }
    }

    async exportData() {
        try {
            // 构建导出参数
            const params = new URLSearchParams({
                ...this.filters,
                sort_field: this.sortField,
                sort_order: this.sortOrder
            });

            // 这里需要添加导出API调用
            // 由于我们还没有实现后端的导出API，这里先模拟
            alert('数据导出功能正在开发中...');
            console.log('导出参数:', params.toString());

        } catch (error) {
            alert('导出失败: ' + error.message);
        }
    }
}

// 页面加载完成后初始化
$(document).ready(function() {
    window.dataManagement = new DataManagement();
});